<template>
  <el-dialog :title="title" custom-class="supplies-dialog" :close-on-click-modal="false" :modal="false"
    :visible.sync="open" :before-close="handleClose">
    <el-form ref="form" :class="readonly ? 'detail' :'edit'" inline label-suffix=":" size="small" :rules="rules"
      :model="formData" hide-required-asterisk >
      <el-row>
        <el-col :span="12">
          <el-form-item label="物资编号" prop="suppliesNum">
            <el-input v-model="formData.suppliesNum" :readonly="readonly"></el-input>
          </el-form-item>
      </el-col>
        <el-col :span="12">
          <el-form-item label="物资名称" prop="suppliesName">
            <el-input v-model="formData.suppliesName" :readonly="readonly"></el-input>
          </el-form-item>
      </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="物资类型" prop="typeId">
            <el-select v-model="formData.typeId" disabled>
              <el-option v-for="opt in suppliesTypeList" :key="opt.typeId" :label="opt.typeName" :value="opt.typeId">
              </el-option>
            </el-select>
          </el-form-item>
      </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" disabled>
              <el-option v-for="opt in statusOption" :key="opt.value" :label="opt.label" :value="opt.value"></el-option>
            </el-select>
          </el-form-item>
      </el-col>
      </el-row>
      
      <el-divider>人 员 信 息</el-divider>
      <div class="tools" v-if="submitBtn">
        <el-button @click="handleSelect" size="mini" :disabled="toolBtnDistabled()">选择</el-button>
        <el-button @click="handleAdd" :disabled="toolBtnDistabled()" size="mini">添加</el-button>
        <span class="person-rule">{{ personValid }}</span>
      </div>
      <el-scrollbar class="person-scrollbar" wrap-class="person-scrollbar__wrap">
        <div v-for="(item, index) in formData.personList" :key="index" class="person-item">
          <div class="operation" v-if="submitBtn" @click="handleDelete(item, formData.personList)">
            <svg-icon icon-class="delete"></svg-icon>
          </div>
          <div>
            <el-upload class="person-pic" :headers="uploadHeaders" :action="actionUrl" :accept="acceptType"
              :disabled="!submitBtn" :show-file-list="false"
              :on-success="(response, file) => onSuccess(response, file, item)">
              <img :src="item.localUrl || item.pic" v-if="item.pic || item.localUrl" />
            </el-upload>
          </div>
          <div>
            <el-form-item label="姓名" :prop="`personList[${index}].personName`" :rules="personRules.personName">
              <el-input v-model="item.personName" :readonly="item.personId ? true : false"></el-input>
            </el-form-item>
            <el-form-item label="职务">
              <el-input v-model="item.dutyName" :readonly="item.personId ? true : false"></el-input>
            </el-form-item>
            <el-form-item label="部门">
              <el-input v-model="item.groupName" :readonly="item.personId ? true : false"></el-input>
            </el-form-item>
            <el-form-item label="年龄" >
              <el-input v-model="item.age" :readonly="item.personId ? true : false"></el-input>
            </el-form-item>
            <el-form-item label="电话" :prop="`personList[${index}].personTel`" :rules="personRules.personTel">
              <el-input v-model="item.personTel" :readonly="item.personId ? true : false"></el-input>
            </el-form-item>
          </div>
        </div>
      </el-scrollbar>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleEdit(submitBtn)" :disabled="commitDisabled" size="small">{{ submitBtn ? '确 定' : '编 辑' }}
      </el-button>
      <el-button @click="handleClose" size="small">取 消</el-button>
    </div>
    <!-- 人员选择 -->
    <person-dialog v-if="openPersonDialog" :open.sync="openPersonDialog" @commit="onSelected"></person-dialog>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'

import PersonDialog from './PersonDialog'

import { modifySupplies } from '@/api/supplies'

export default {
  props: {
    open: Boolean,
    title: String,
    formData: Object,
  },
  components: {
    PersonDialog,
  },
  computed: {
    ...mapGetters(['suppliesTypeList']),
  },
  data() {
    return {
      readonly: true,
      disabled: true,
      submitBtn: false,
      checkedPerson: [],
      statusOption: [
        {
          label: '在线',
          value: 0,
        },
        {
          label: '离线',
          value: 1,
        },
      ],
      rules: {
        suppliesNum: [
          {
            required: true,
            message: '物资编号不能为空',
            trigger: 'blur',
          },
        ],
        suppliesName: [
          {
            required: true,
            message: '物资名称不能为空',
            trigger: 'blur',
          },
        ],
      },
      personRules: {
        personName: [
          {
            required: true,
            message: '姓名不能为空',
            trigger: 'blur',
          },
        ],
        personTel: [
          {
            required: true,
            message: '电话不能为空',
            trigger: 'blur',
          },
        ],
      },
      personValid: '',

      uploadHeaders: {
        ContentType: 'multipart/form-data',
        Authorization: sessionStorage.getItem('tokenSign'),
      },
      // actionUrl: 'http://zhangrr.utools.club/materials/person/imgUpload',
      actionUrl: '/materials/person/imgUpload',
      acceptType: 'image/*', //图片格式
      commitDisabled: false, // 提交按钮

      openPersonDialog: false,
    }
  },
  watch: {
    'formData.personList'(newValue) {
      if (newValue.length > 0) {
        this.personValid = ''
      }
    },
  },
  methods: {
    // 文件上传成功
    onSuccess(response, file, item) {
      console.log('onSuccess', response, item)
      let URL
      if (window.createObjectURL != undefined) {
        // basic
        URL = window.createObjectURL(file.raw)
      } else if (window.URL != undefined) {
        // mozilla(firefox)
        URL = window.URL.createObjectURL(file.raw)
      } else if (window.webkitURL != undefined) {
        // webkit or chrome
        URL = window.webkitURL.createObjectURL(file.raw)
      }
      item.localUrl = URL
      item.pic = response.true
    },
    handleDelete(person, list) {
      console.log('handleDelete', person, list)
      let index = list.indexOf(person)
      if (index !== -1) {
        list.splice(index, 1)
      }
    },
    // 按钮是否禁用
    toolBtnDistabled() {
      if (this.formData.type === 'label') {
        return this.formData.personList.length > 0
      }
      return false
    },
    // 选择人员
    handleSelect() {
      console.log('handleSelect')
      this.openPersonDialog = true
    },
    // 选择人员回调
    onSelected(rows) {
      if (rows.length > 0) {
        let list = this.formData.personList
        rows.forEach((row) => {
          if (!list.some((item) => item.personId === row.personId)) {
            list.push(row)
          }
        })
      }
    },
    // 添加人员
    handleAdd() {
      console.log('handleAdd')
      let person = {
        personName: '',
        personTel: '',
        pic: '',
        age: undefined,
        groupName: '',
        dutyName: '',
      }
      this.formData.personList.push(person)
    },
    // 编辑图片
    handlePic() {
      console.log('handlePic')
      if (this.submitBtn) {
        console.log('handlePic upload')
      }
    },
    //编辑
    handleEdit(submitBtn) {
      if (!submitBtn) {
        this.readonly = false
        this.disabled = false
        this.submitBtn = true
      } else {
        console.log('commit')
        let form = this.formData
        this.commitDisabled = true
        this.$refs['form'].validate((valid) => {
          if (valid) {
            console.log('submit!')
            if (form.personList.length === 0) {
              this.personValid = '请选择或添加人员'
              this.commitDisabled = false
              return
            }
            if (form.type === 'label' && form.personList.length > 1) {
              this.personValid = '定位标签只能绑定一个人员'
              this.commitDisabled = false
              return
            }
            console.log('form', form)
            // 提交表单
            modifySupplies(form)
              .then((res) => {
                this.handleClose()
                this.$emit('update', {
                  suppliesId: form.suppliesId,
                  data: '',
                  obj: form,
                })
              })
              .catch((err) => {
                console.log(err)
                this.commitDisabled = false
              })
          } else {
            this.commitDisabled = false
          }
        })
      }
    },
    // 关闭或取消
    handleClose() {
      console.log('handleClose')
      this.$emit('update:open', false)
    },
  },
  mounted() {},
}
</script>

<style lang="scss" scoped>
@import '~@/assets/scss/supplies_dialog.scss';
</style>
